package me.fenglu.deployserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.compress.compressors.CompressorStreamFactory;

public class DeployHandler implements Runnable {

	private Socket client;
	private int clientNum;
	
	public DeployHandler(Socket client, int clientNum) {
		super();
		this.client = client;
		this.clientNum = clientNum;
	}
	
	@Override
	public void run() {
		System.err.println("client ["+clientNum +"] is connected!");
		InputStream downstream = null;
		OutputStream upstream = null;
		try {
			downstream = client.getInputStream();
			upstream = client.getOutputStream();
			int size = downstream.read();
			DataOutputStream dos = new DataOutputStream(upstream);
			dos.writeUTF("Got size! size = "+size);
			
			BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			FileOutputStream fos = null;
			
			byte[] buffer = new byte[102400];
			bis = new BufferedInputStream(downstream);
			int len = 0;
			
			
			
			String targetFilePath = DeployServer.rootPath + "code.tar.gz";
			File targetFile = new File(targetFilePath);
			if(!targetFile.exists()) {
				targetFile = new File(targetFilePath.substring(0, targetFilePath.lastIndexOf("/")));
				targetFile.mkdirs();
			}
			
			fos = new FileOutputStream(targetFilePath);
			bos = new BufferedOutputStream(fos);
			while(-1 != (len = bis.read(buffer))) {
System.err.println(len);				
				bos.write(buffer, 0, len);
				bos.flush();
				buffer = new byte[102400];
			}
			bis.close();
			bos.close();
			
			//FileDecompressor.deTar("/home/king/Desktop/", CompressorStreamFactory.GZIP);
			FileDecompressor.deTar("D:\\WORK\\apache-tomcat-8.0.28\\webapps\\wygz_wx\\", CompressorStreamFactory.GZIP);
			
			//Process p = Runtime.getRuntime().exec("D:\\WORK\\apache-tomcat-8.0.28\\bin\\startup.bat");
			
			Runtime runtime = Runtime.getRuntime();
			
			Process process = Runtime.getRuntime().exec("cmd /c  D:\\WORK\\apache-tomcat-8.0.28\\bin\\startup.bat", null, new File("D:\\WORK\\apache-tomcat-8.0.28\\")); // 调用外部程序
		    final InputStream in = process.getInputStream();
		    BufferedReader br=new BufferedReader(new InputStreamReader(in));
		    StringBuilder buf = new StringBuilder();
		    String line = null;
		    while((line = br.readLine()) != null)
		    buf.append(line);
		    System.out.println("输出结果为：" + buf);
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			System.err.println("client ["+clientNum +"] is disconnected!");
		}
	}
}
